<template>
    <div>
        <el-dialog v-model="state.dialog.show" title="编辑文章"
                   :fullscreen="true"
                   :show-close="false"
                   :close-on-press-escape="false"
                   :close-on-click-modal="false"
        >
            <el-form ref="dialogFormRef" :model="state.form" :rules="state.rules" label-width="120px"
                     size="default">
                <el-row :gutter="35">
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-form-item label="文章" prop="content">
                            <markdown-editor
                                :mode="'split'"
                                :render="renderFunction"
                                v-model="state.form.content"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
				<span class="dialog-footer">
					<el-button size="default" @click="onCancel">取 消</el-button>
					<el-button size="default" type="info" @click="onSave">保 存</el-button>
					<el-button size="default" type="primary" @click="openSetting">设 置</el-button>
				</span>
            </template>
        </el-dialog>
        <Setting ref="settingRef" @confirm="settingOk" @cancel="openTimer"/>
    </div>
</template>

<script lang="ts" setup>
import {defineAsyncComponent, reactive, ref} from 'vue';
import stores from "/@/stores";
import {commonApi} from "/@/api/common";
import {onBeforeUnmount} from "vue-demi";
import {articleApi} from "/@/api/article";
import {draftApi} from "/@/api/draft";
import {ElMessageBox} from "element-plus";

const MarkdownEditor = defineAsyncComponent(() => import('/@/components/editor/MarkdownEditor.vue'));
const Setting = defineAsyncComponent(() => import('/@/views/article/Setting.vue'));
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const settingRef = ref()
// 定义变量内容
const dialogFormRef = ref();
const state = reactive<DialogState<DraftSaveOrUpdateDto>>({
    form: {
        content: "",
        id: undefined,
    },
    dialog: {
        show: false
    },
    rules: {}
});

const renderFunction = (markdown: string) => {
    return commonApi.renderMarkdown(markdown)
}

// 打开弹窗
const openDialog = async (articleVo: ArticleVo) => {
    stores.commonStoreState.openLoading()
    state.form.id = articleVo.id
    const draftVo = await draftApi.getDraft(articleVo.id);
    stores.commonStoreState.closeLoading()
    state.form.content = articleVo.content;
    state.dialog.show = true;
    if (draftVo?.content && draftVo.content !== articleVo.content) {
        //存在草稿，并且草稿内容和文章不一致
        ElMessageBox.confirm(`文章《${articleVo.title}》存在没有保存的草稿内容，是否恢复？`, '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        })
            .then(async () => {
                state.form.content = draftVo.content;
            }).finally(() => {
            openTimer();
        });
    } else {
        openTimer();
    }
};
// 关闭弹窗
const closeDialog = () => {
    //只能重置表单字段
    dialogFormRef.value?.resetFields();
    state.dialog.show = false;
};

// 发布时打开设置弹窗，首先保存文章
const openSetting = async () => {
    stores.commonStoreState.openLoading()
    const articleVo = await saveArticle();
    stores.commonStoreState.closeLoading()
    settingRef.value.openDrawer(articleVo)
}

//保存文章
const saveArticle = async () => {
    closeTimer();
    await saveDraft();
    return await articleApi.saveOrUpdateArticle({
        id: state.form.id,
    });
}
//保存草稿
const saveDraft = async () => {
    let draftVo = await draftApi.saveOrUpdateDraft(state.form);
    state.form.id = state.form.id || draftVo.id
    return draftVo;
}
//取消按钮
const onCancel = async () => {
    closeTimer()
    if (state.form.id) {
        //取消后删除草稿
        await draftApi.deleteDraft(state.form.id)
    }
    closeDialog()
    // emit("refresh")
}
//保存按钮
const onSave = async () => {
    stores.commonStoreState.openLoading()
    await saveArticle();
    closeDialog();
    emit("refresh");
    stores.commonStoreState.closeLoading()
}

const settingOk = async () => {
    closeDialog()
    emit("refresh")
}

const timerId = ref()
const openTimer = () => {
    closeTimer()
    timerId.value = setInterval(saveDraft, 60000);
}
const closeTimer = () => {
    clearInterval(timerId.value);
    timerId.value = undefined;
}
onBeforeUnmount(() => {
    // 在组件销毁前清除定时器
    closeTimer()
});
// 暴露变量
defineExpose({
    openDialog,
});
</script>
